<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 px-4">
    <n-card class="w-full max-w-lg py-12">
      <h2 class="text-2xl font-bold mb-6 text-blue-600">语音识别</h2>
      <form @submit.prevent="onSubmit" class="flex flex-col gap-4">
        <input type="file" accept="audio/*" @change="onFileChange" class="n-input" />
        <n-button type="primary" block :disabled="!audioFile" attr-type="submit">上传并识别</n-button>
      </form>
      <n-spin v-if="loading" class="mt-4">识别中...</n-spin>
      <n-alert v-if="result" type="success" class="mt-4">
        <template #header>识别结果</template>
        <pre class="whitespace-pre-wrap">{{ result }}</pre>
      </n-alert>
      <n-alert v-if="error" type="error" class="mt-2">{{ error }}</n-alert>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { recognizeVoice } from '../api/voice';

const audioFile = ref<File|null>(null);
const result = ref('');
const error = ref('');
const loading = ref(false);

const onFileChange = (e: Event) => {
  const files = (e.target as HTMLInputElement).files;
  if (files && files.length > 0) {
    audioFile.value = files[0];
  } else {
    audioFile.value = null;
  }
};

const onSubmit = async () => {
  if (!audioFile.value) return;
  error.value = '';
  result.value = '';
  loading.value = true;
  const formData = new FormData();
  formData.append('file', audioFile.value);
  try {
    const res = await recognizeVoice(formData);
    result.value = res.data?.result || JSON.stringify(res.data);
  } catch (e: any) {
    error.value = e.response?.data?.message || '识别失败';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.voice-recognition {
  max-width: 600px;
  margin: 40px auto;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}
</style> 